//
//  ViewController.swift
//  PagerStripDemo
//
//  Created by Sayalee on 4/19/18.
//  Copyright © 2018 Assignment. All rights reserved.

import UIKit
import XLPagerTabStrip

class PlaceListVC: ButtonBarPagerTabStripViewController {
    
    //    var dataset: placeData?
    @IBOutlet var buttons: [UIButton]!
    @IBOutlet weak var filteringButtonBackgroundView: UIView!
    @IBOutlet weak var nearStationButtonWidthConstant: NSLayoutConstraint!
    @IBOutlet weak var keywordButtonWidthConstant: NSLayoutConstraint!
    @IBOutlet weak var usefulInfoButtonWidthConstant: NSLayoutConstraint!
    
    var keywordData: [KeywordData] = []
    var usefulData: [UsefulInformData] = []
    
    lazy var keywordModal: KeywordLauncher = {
        let launcher = KeywordLauncher()
        launcher.searchVC = self
        return launcher
    }()
    
// MARK: - View LifeCycle
    override func viewDidLoad() {
        configureButtonBar()
        super.viewDidLoad() // 순서가 독특하네욤
        setNavigationBar()
        set()
        setButtons()
        addObserver()
        setDefaultRequest()
        setupActivityIndicator()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupShadowButtonBackgroundView()
        restoreUserdefaults()

    }
    
    @IBAction func nearstationButtonAction (_ sender: Any) {
        let sb = UIStoryboard.init(name: "Write", bundle: nil)
        let vc = sb.instantiateViewController(withIdentifier: "subwayNavigation")
        present(vc, animated: true)
    }
    
    @IBAction func keywordButtonAction(_ sender: Any) {
        keywordModal.showSettings("키워드", keywordData)
    }
    
    @IBAction func usefulInfoButtonAction(_ sender: Any) {
        keywordModal.showSettings("장소 정보", usefulData)
    }
    
//MARK: - restore userdefaults
    func restoreUserdefaults() {
        let defaults = UserDefaults.standard
        defaults.set([], forKey: "keyword")
        defaults.set([], forKey: "subway")
        defaults.set([], forKey: "useful")
    }
    
//MARK: - PagerTabDelegate
    func set() {
        changeCurrentIndexProgressive = { (oldCell: ButtonBarViewCell?, newCell: ButtonBarViewCell?, progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in
            guard changeCurrentIndex == true else { return }

            oldCell?.label.textColor = UIColor.gray40
            newCell?.label.textColor = UIColor.black

            if animated {
                UIView.animate(withDuration: 0.1, animations: { () -> Void in
                    newCell?.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
                    oldCell?.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
                })
            }
            else {
                newCell?.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
                oldCell?.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
            }
        }
    }
    
    func configureButtonBar() {
        settings.style.buttonBarBackgroundColor = .white
        settings.style.buttonBarItemBackgroundColor = .white
        
        settings.style.buttonBarItemFont = .boldSystemFont(ofSize: 15)
        settings.style.buttonBarItemTitleColor = UIColor.gray40
        
        settings.style.buttonBarMinimumLineSpacing = 0
        settings.style.buttonBarItemsShouldFillAvailableWidth = true
        settings.style.buttonBarLeftContentInset = 0
        settings.style.buttonBarRightContentInset = 0
        
        settings.style.selectedBarHeight = 3.0
        settings.style.selectedBarBackgroundColor = .black
        
        // Changing item text color on swipe
        changeCurrentIndexProgressive = { [weak self] (oldCell: ButtonBarViewCell?, newCell: ButtonBarViewCell?, progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in
            guard changeCurrentIndex == true else { return }
            oldCell?.label.textColor = .gray
            newCell?.label.textColor = .black
        }
    }
    
    
// MARK: - PagerTabStripDataSource
    override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
        
        let child1 = UIStoryboard.init(name: "PlaceList", bundle: nil).instantiateViewController(withIdentifier: "ChildViewController") as! ChildVC
        child1.childNumber = "전체"
        
        let child2 = UIStoryboard.init(name: "PlaceList", bundle: nil).instantiateViewController(withIdentifier: "ChildViewController") as! ChildVC
        child2.childNumber = "맛집"
        
        let child3 = UIStoryboard.init(name: "PlaceList", bundle: nil).instantiateViewController(withIdentifier: "ChildViewController") as! ChildVC
        child3.childNumber = "술집"
        
        let child4 = UIStoryboard.init(name: "PlaceList", bundle: nil).instantiateViewController(withIdentifier: "ChildViewController") as! ChildVC
        child4.childNumber = "카페"
        
        let child5 = UIStoryboard.init(name: "PlaceList", bundle: nil).instantiateViewController(withIdentifier: "ChildViewController") as! ChildVC
        child5.childNumber = "스터디"
        
        let child6 = UIStoryboard.init(name: "PlaceList", bundle: nil).instantiateViewController(withIdentifier: "ChildViewController") as! ChildVC
        child6.childNumber = "기타"
        
        return [child1, child2, child3, child4, child5, child6]
    }

//MARK: - Navigation, Button, Notification, Shadow, activityIndicator
    
    private func setupActivityIndicator() {
        // 로딩뷰
        self.view.addActivityIndicator()
        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
            self.view.removeActivityIndicator()
        })
    }
    
    private func setupShadowButtonBackgroundView() {
        let color = UIColor.gray80
        let opacity: Float = 0.2
        let offset: CGSize = CGSize(width: 0, height: 5)
        let radius: CGFloat = 5
        
        filteringButtonBackgroundView.makeShadow(color, opacity, offset, radius)
    }
    
    private func addObserver() {
        NotificationCenter.default.addObserver(self, selector: #selector(buttonHidden), name: .changeChildViewVC, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(configureSubwayButton(_:)), name: .searchSubwayNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(configureKeywordButton), name: .homeModalKeywordNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(configureUsefulButton(_:)), name: .homeModalUsefulNotification, object: nil)
    }
    
    func changeTabBar(hidden: Bool, animated: Bool){
        guard let tabBar = self.tabBarController?.tabBar else { return }
        if tabBar.isHidden == hidden{ return }
        let frame = tabBar.frame
        let offset = hidden ? frame.size.height : -frame.size.height
        let duration: TimeInterval = (animated ? 0.5 : 0.0)
        tabBar.isHidden = false
        
        UIView.animate(withDuration: duration, animations: {
            tabBar.frame = frame.offsetBy(dx: 0, dy: offset)
        }, completion: { (true) in
            tabBar.isHidden = hidden
        })
    }
    
    @objc
    func configureKeywordButton(_ notification: NSNotification) {
        guard let injectedModel = notification.userInfo?["indexPath.item"] as? [Int] else { return }
        
        print(injectedModel)
        
        if injectedModel.count != 0 {
            buttons[1].setTitle(String(describing: "키워드 \(injectedModel.count)개"), for: .normal)
            buttons[1].setTitleColor(UIColor.white, for: .normal)
            buttons[1].backgroundColor = UIColor.warmPink
            buttons[1].titleLabel?.font = .boldSystemFont(ofSize: 13)
            buttons[1].layer.borderColor = UIColor.warmPink.cgColor
            buttons[1].layer.borderWidth = 1
            buttons[1].setImage(UIImage(named: "whiteDownArrowIc"), for: .normal)
            keywordButtonWidthConstant.constant = 92
            UIView.animate(withDuration: 0.3,
                           animations: {
                            self.view.layoutIfNeeded()
            })
        } else {
            restoreOriginKeywordButton()
        }
    }
    
    @objc
    func configureUsefulButton(_ notification: NSNotification) {
        guard let injectedModel = notification.userInfo?["indexPath.item"] as? [Int] else { return }
        
        print(injectedModel)
        
        if injectedModel.count != 0 {
            buttons[2].setTitle(String(describing: "장소 정보 \(injectedModel.count)개"), for: .normal)
            buttons[2].setTitleColor(UIColor.white, for: .normal)
            buttons[2].backgroundColor = UIColor.warmPink
            buttons[2].titleLabel?.font = .boldSystemFont(ofSize: 13)
            buttons[2].layer.borderColor = UIColor.warmPink.cgColor
            buttons[2].layer.borderWidth = 1
            buttons[2].setImage(UIImage(named: "whiteDownArrowIc"), for: .normal)
            usefulInfoButtonWidthConstant.constant = 106
            UIView.animate(withDuration: 0.3,
                           animations: {
                            self.view.layoutIfNeeded()
            })
        } else {
            restoreOriginUsefulInfoButton()
        }
    }
    
    @objc
    func configureSubwayButton(_ notification: NSNotification) {
        guard let injectedModel = notification.userInfo?["model"] as? [SubwayData] else { return }
        
        if injectedModel.count != 0 {
            buttons[0].setTitle(String(describing: "주변역 \(injectedModel.count)개"), for: .normal)
            buttons[0].setTitleColor(UIColor.white, for: .normal)
            buttons[0].backgroundColor = UIColor.warmPink
            buttons[0].titleLabel?.font = .boldSystemFont(ofSize: 13)
            buttons[0].layer.borderColor = UIColor.warmPink.cgColor
            buttons[0].layer.borderWidth = 1
            buttons[0].setImage(UIImage(named: "whiteDownArrowIc"), for: .normal)
            nearStationButtonWidthConstant.constant = 92
            UIView.animate(withDuration: 0.3,
                           animations: {
                            self.view.layoutIfNeeded()
            })
        } else {
            restoreOriginSubwayButton()
        }
    }
    
    @objc
    func buttonHidden(_ notification: NSNotification) {
        guard let childNumber = notification.userInfo?["childNumber"] as? String else { return }
//        print("childNumber: \(childNumber)")
        
        restoreOriginKeywordButton()
        restoreOriginSubwayButton()
        restoreOriginUsefulInfoButton()
        
        if childNumber == "전체" {
            buttons[1].isHidden = true
            buttons[2].isHidden = true
        } else {
            buttons.forEach({
                $0.isHidden = false
            })
        }
    }
    
    func setButtons() {
        for i in 0..<3 {
            buttons[i].layer.cornerRadius = 4
        }
    }
    
    func getWidth(text: String) -> CGFloat {
        let txtField = UITextField(frame: .zero)
        txtField.text = text
        txtField.sizeToFit()
        return txtField.frame.size.width
    }
    
    private func setNavigationBar() {
        guard let navigationBar = self.navigationController?.navigationBar else { return }
        
        navigationBar.isTranslucent = true
        navigationBar.backgroundColor = UIColor.clear
        navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        navigationBar.shadowImage = UIImage()
        
        let titleLabel = UILabel()
        titleLabel.text = "플레이스"
        titleLabel.font = UIFont.boldSystemFont(ofSize: 18)
        titleLabel.sizeToFit()
        
        let leftItem = UIBarButtonItem(customView: titleLabel)
        navigationItem.leftBarButtonItem = leftItem
    }
}

//MARK: - Button View Layout 따로 뺐어욤
extension PlaceListVC {
    
    func restoreOriginSubwayButton() {
        buttons[0].setTitle(String("주변역"), for: .normal)
        buttons[0].setTitleColor(UIColor.gray90, for: .normal)
        buttons[0].backgroundColor = UIColor.gray10
        buttons[0].titleLabel?.font = .boldSystemFont(ofSize: 13)
        buttons[0].layer.borderColor = UIColor.gray10.cgColor
        buttons[0].layer.borderWidth = 1
        buttons[0].setImage(UIImage(named: "downArrowIc"), for: .normal)
        nearStationButtonWidthConstant.constant = 72
        UIView.animate(withDuration: 0.3,
                       animations: {
                        self.view.layoutIfNeeded()
        })
    }
    func restoreOriginKeywordButton() {
        buttons[1].setTitle(String("키워드"), for: .normal)
        buttons[1].setTitleColor(UIColor.gray90, for: .normal)
        buttons[1].backgroundColor = UIColor.gray10
        buttons[1].titleLabel?.font = .boldSystemFont(ofSize: 13)
        buttons[1].layer.borderColor = UIColor.gray10.cgColor
        buttons[1].layer.borderWidth = 1
        buttons[1].setImage(UIImage(named: "downArrowIc"), for: .normal)
        keywordButtonWidthConstant.constant = 72
        UIView.animate(withDuration: 0.3,
                       animations: {
                        self.view.layoutIfNeeded()
        })
    }
    func restoreOriginUsefulInfoButton() {
        buttons[2].setTitle(String("장소 정보"), for: .normal)
        buttons[2].setTitleColor(UIColor.gray90, for: .normal)
        buttons[2].backgroundColor = UIColor.gray10
        buttons[2].titleLabel?.font = .boldSystemFont(ofSize: 13)
        buttons[2].layer.borderColor = UIColor.gray10.cgColor
        buttons[2].layer.borderWidth = 1
        buttons[2].setImage(UIImage(named: "downArrowIc"), for: .normal)
        usefulInfoButtonWidthConstant.constant = 87
        UIView.animate(withDuration: 0.3,
                       animations: {
                        self.view.layoutIfNeeded()
        })
    }
}

//MARK: - 통신
extension PlaceListVC {
    func setDefaultRequest() {
        KeywordServices.keywordServices.getKeywordRequest { data in
            if let metaData = data {
                self.keywordData = metaData
            }
        }
        UsefulInformServices.usefulInformServices.getKeywordRequest { data in
            if let metaData = data {
                self.usefulData = metaData
            }
        }
    }
}

extension UIButton {
    func centerTextAndImage(spacing: CGFloat) {
        let insetAmount = spacing / 2
        imageEdgeInsets = UIEdgeInsets(top: 0, left: -insetAmount, bottom: 0, right: insetAmount)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: -insetAmount)
        contentEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: insetAmount)
    }
}




